/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component, Fragment} from 'react';
import {
  Form, Input, Radio, Select, Icon,
  Upload, Descriptions, DatePicker, TreeSelect, InputNumber, Button
} from 'antd';
import {connect} from 'dva';
import find from 'lodash/find'
import request from '@/utils/request';
import ReactDataGrid from "react-data-grid";
import Loading from "@/components/Loading";
import MyPagination from "@/components/MyPagination";
import {renderTreeNodes} from "@/utils/utils";
import filter from 'lodash/filter'
import RightTable from './RightTable'
const FormItem = Form.Item;
const {TextArea} = Input;
const TreeNode = TreeSelect.TreeNode;
const RadioGroup = Radio.Group;
const Option = Select.Option;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meters: [],
      origin_meters:[],
      nodeDataArray: [],
      type: this.props.editRecord.type,
      villages: [],
      all_workstations: [],
      origin_all_workstations:[],
      data: [],
      selected_data: [],
      editRecord: {},
      all_regions: [],
      meta: {total: 0, per_page: 30, current_page: 1},
      searchParams: {
        number: '',
        user_number: '',
        communication_type: '',
        region_id: '',
        region_name: '',
        status: '1',
        caliber: '',
        address: '',
        imei: '',
        page: 1,
        per_page: 50,
      },
      all_vendors: [],
      selectedRowKeys: [],
      selectedSelectedRowKeys: [],
      loading: false
    };
  }

  componentDidMount() {
    console.log('exitJson', this.props.exitJson)
    const type = this.state.type
    if (type === 1) {
      this.getType1()
    } else if (type === 4) {
      this.getType4()
    } else if (type === 5) {
      this.getType5()
    } else if (type === 6) {
      console.log(this.props.exitJson.nodeDataArray)
      this.getType6()
    }
  }

  getType1 = () => {//普通水表
    const that = this
    request(`/join_area_meters`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          meters: response.data.data,
          origin_meters: response.data.data,
          nodeDataArray: this.props.exitJson.nodeDataArray
        });
      }
    });
  }
  getType2 = () => {//虚拟水表（流入流出型）

  }
  getType3 = () => {//虚拟水表（只流出型）

  }
  getType4 = () => {//工作站
    const that = this
    request(`/join_area_workstations`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_workstations: response.data.data,
          origin_all_workstations: response.data.data,
        })
      }
    })
  }
  getType5 = () => {//下级DMA分区
    const that = this
    request(`/areas`, {
      method: 'GET',
      params: {
        return: 'all'
      }
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          villages: response.data.data
        })
      }
    })
  }
  getType6 = () => {//工作站
    this.handleSearch(this.state.searchParams);
    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });

    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_regions: response.data.data,
        });
      }

    });
    if(find(this.props.exitJson.nodeDataArray,o=>o.key===this.props.editRecord.key).sub_vertexs){
      this.setState({
        selected_data:find(this.props.exitJson.nodeDataArray,o=>o.key===this.props.editRecord.key).sub_vertexs.map((item)=>{
          return {...item,id:item.key}
        })
      })
    }

  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode value={item.id} title={item.name} key={item.id}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode value={item.id} title={item.name} key={item.id}/>
    });
  }
  onRowsSelected = (rows) => {
    console.log(1.1)
    let selectedRowKeys = this.state.selectedRowKeys
    this.setState({
      selectedRowKeys: selectedRowKeys.concat(rows.map(r => r.rowIdx))
    })
  };
  onRowsDeselected = (rows) => {
    console.log(1.2)
    let rowIndexes = rows.map(r => r.rowIdx);
    let selectedRowKeys = this.state.selectedRowKeys
    this.setState({
      selectedRowKeys: selectedRowKeys.filter(i => rowIndexes.indexOf(i) === -1)
    })
  };
  onSelectedRowsSelected = (rows) => {
    console.log(2.1)
    let selectedRowKeys = this.state.selectedSelectedRowKeys
    this.setState({
      selectedSelectedRowKeys: selectedRowKeys.concat(rows.map(r => r.rowIdx))
    })
  };
  onSelectedRowsDeselected = (rows) => {
    console.log(2.2)
    let rowIndexes = rows.map(r => r.rowIdx);
    let selectedRowKeys = this.state.selectedSelectedRowKeys
    this.setState({
      selectedSelectedRowKeys: selectedRowKeys.filter(i => rowIndexes.indexOf(i) === -1)
    })
  };
  toRight=()=>{
    console.log(this.state.selectedRowKeys)
    const that=this
    const selectedRowKeys=this.state.selectedRowKeys
    for(let i=0;i<selectedRowKeys.length;i++){
      if(selectedRowKeys[i]>=0){
        let rightTableExit=find(this.state.selected_data,function (o){
          return o.number===that.state.data[selectedRowKeys[i]].number
        })
        console.log(rightTableExit)
        if(!rightTableExit){
          this.state.selected_data.unshift(this.state.data[selectedRowKeys[i]])
        }

      }
    }
    this.setState({
      selected_data:this.state.selected_data,
      selectedSelectedRowKeys:[]
    })

  }
  toLeft=()=>{
    let selectedSelectedRowKeys=this.state.selectedSelectedRowKeys
    selectedSelectedRowKeys.sort((a, b) => b - a)
    for (let i = 0; i < selectedSelectedRowKeys.length; i++) {
      this.state.selected_data.splice(selectedSelectedRowKeys[i], 1); // 使用 splice() 方法删除指定下标的元素
    }
    this.setState({
      selected_data:this.state.selected_data,
      selectedSelectedRowKeys:[]
    })
  }
  renderSimpleForm() {
    const all_regions = this.state.all_regions;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const searchParams =this.state.searchParams;
    const username=sessionStorage.getItem('username')
    return (
      <Form layout="inline" className="search-form" style={{marginBottom:'10px'}}>
        <FormItem label="区域">
          {getFieldDecorator('region_id', {
            initialValue: searchParams.region_id?`${searchParams.region_id}$${searchParams.region_name}`:'',
          })(
            <TreeSelect
              style={{ width: '100px' }}
              allowClear
              treeDefaultExpandAll
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              showSearch
            >
              {renderTreeNodes(all_regions)}
            </TreeSelect>,
          )}
        </FormItem>
        <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '100px' }} allowClear disabled={Boolean(username==='宁波水表'||username==='竞达水表'||username==='西安旌旗'||username==='泰安水表'||username==='泰安新贝水表')}>
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('number', {
            initialValue: searchParams.number,
          })(<Input style={{ width: '100px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="安装地址">
          {getFieldDecorator('address', {
            initialValue: searchParams.address,
          })(<Input style={{ width: '120px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  region_id:fieldsValue.region_id?fieldsValue.region_id.split('$')[0]:'',
                  region_name:fieldsValue.region_id?fieldsValue.region_id.split('$')[1]:'',
                  name:''
                });

              });
            }}
          >
            查询
          </Button>
        </FormItem>

      </Form>
    );
  }
  renderSimpleFormWorkStation() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const username=sessionStorage.getItem('username')
    return (
      <Form layout="inline" className="search-form" style={{marginBottom:'10px'}}>
        <FormItem label="名称">
          {getFieldDecorator('name', {
            initialValue: '',
          })(<Input style={{ width: '160px' }} placeholder="请输入"/>)}
        </FormItem>

        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                console.log('fieldsValue',fieldsValue)
                if (err) return;
                const join_area_workstations=filter(this.state.origin_all_workstations,function (item){
                  return (item.name.indexOf(fieldsValue.name)>=0)
                })
                this.setState({
                  all_workstations:join_area_workstations
                })

              });
            }}
          >
            查询
          </Button>
        </FormItem>

      </Form>
    );
  }
  renderSimpleFormMeter() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const username=sessionStorage.getItem('username')
    return (
      <Form layout="inline" className="search-form" style={{marginBottom:'10px'}}>
        <FormItem label="地址">
          {getFieldDecorator('address', {
            initialValue: '',
          })(<Input style={{ width: '160px' }} placeholder="请输入"/>)}
        </FormItem>
     {/*   <FormItem label="水表号">
          {getFieldDecorator('number', {
            initialValue: '',
          })(<Input style={{ width: '160px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                console.log('fieldsValue',fieldsValue)
                if (err) return;
                const join_area_meters=filter(this.state.origin_meters,function (item){
                  return (item.address.indexOf(fieldsValue.address)>=0)
                })
                this.setState({
                  meters:join_area_meters
                })

              });
            }}
          >
            查询
          </Button>
        </FormItem>

      </Form>
    );
  }
  handleSearch = (values) => {
    console.log('values',values)
    const that = this
    this.setState({
      loading: true
    })
    request(`/meters`, {
      method: 'GET',
      params: {
        ...values
      }
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
          meta: response.data.meta,
          loading: false,
          searchParams: values,
          selectedRowKeys: [],
        })
      }
    })
  }
  handleFormReset = () => {
    const { form } = this.props;
    const username=sessionStorage.getItem('username')
    form.resetFields();
    this.handleSearch({
      number: '',
      user_number: '',
      caliber:'',
      address: '',
      communication_type:'',
      status:'1',
      page: 1,
      per_page: 50,
      region_id:'',
      region_name:'',
    });
  };
  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      }
    };
    const {getFieldDecorator} = this.props.form;
    const {data,selected_data, loading, selectedRowKeys,selectedSelectedRowKeys, searchParams, meta} = this.state
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {meta} = this.state;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '水表ID',
        width: 150,
        key: 'id',

      },
      {
        name: '水表号',
        width: 150,
        key: 'number',

      },
      {
        name: '安装地址',
        key: 'address',
        width: 160,
      },
    ].map(c => ({...defaultColumnProperties, ...c}));
    const columns2 = [
      {
        name: '序号',
        width: 50,
        key: '_index2',
        frozen: true,
        formatter: (event) => {
          const {meta} = this.state;
          return <p className={'index'}>{ (event.value + 1)}</p>;
        },
      },
      {
        name: '水表ID',
        width: 150,
        key: 'id',

      },
      {
        name: '水表号',
        width: 150,
        key: 'number',

      },
      {
        name: '安装地址',
        key: 'address',
        width: 160,
      },
    ].map(c => ({...defaultColumnProperties, ...c}));

    const workstationColumns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {meta} = this.state;
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: '名称',
        width: 210,
        key: 'name',

      },
      {
        name: '站点地址',
        key: 'address',
        width: 235,
      },
      {
        name: '操作',
        width: 75,
        key: 'operate',
        formatter: (event) => {
          return this.props.editRecord.key!==event.row.id&&<Button type={'primary'} size={"small"} onClick={()=>{
            console.log('this.props.form.getFieldValue(\'sort\')',this.props.form.getFieldValue('sort'))
            this.props.handleEditWorkstation(event.row.id,event.row.name,this.props.form.getFieldValue('sort'))
          }}>选择</Button>
        },
      },
    ].map(c => ({...defaultColumnProperties, ...c}));
    const meterColumns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {meta} = this.state;
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: '地址',
        width: 210,
        key: 'address',

      },
      {
        name: '水表号',
        key: 'number',
        width: 210,
      },
      {
        name: '操作',
        width: 75,
        key: 'operate',
        formatter: (event) => {
          return this.props.editRecord.key!==event.row.id&&<Button type={'primary'} size={"small"} onClick={()=>{
            console.log('this.props.form.getFieldValue(\'sort\')',this.props.form.getFieldValue('sort'))
            this.props.handleEditWorkstation(event.row.id,event.row.address,this.props.form.getFieldValue('sort'))
          }}>选择</Button>
        },
      },
    ].map(c => ({...defaultColumnProperties, ...c}));

    return (
      <div>
        <Form>
          {
            (this.props.editRecord.type === 6) &&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
              水表群组名称
            </span>
              )}>
              {getFieldDecorator('name', {
                initialValue: this.props.editRecord.name==='水表群组'?'':this.props.editRecord.name,
                // initialValue: this.props.editRecord.name,
                rules: [{required: true, message: ''}],
              })(
                <Input/>
              )}
            </FormItem>
          }
          {
            (this.props.editRecord.type === 2 || this.props.editRecord.type === 3) &&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
              虚拟表名称
            </span>
              )}>
              {getFieldDecorator('name', {
                initialValue: this.props.editRecord.name,
                rules: [{required: true, message: ''}],
              })(
                <Input/>
              )}
            </FormItem>
          }
          {/*{
            (this.props.editRecord.type === 1) &&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
             水表
            </span>
              )}>
              {getFieldDecorator('meter', {
                initialValue: this.props.editRecord ? {
                    key: this.props.editRecord.key,
                    label: this.props.editRecord.name
                  } :
                  {key: '', label: ''},
              })(
                <Select labelInValue={true}>
                  {
                    this.state.meters.map((item, index) => {
                      return <Option key={index} value={item.id.toString()}>{item.address}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
          }*/}
          {
            this.props.editRecord.type === 1 &&
            <div >
              <div style={{padding:'5px 15px 0'}}>{this.renderSimpleFormMeter()}</div>
              <div style={{margin:'0 15px'}}>
                <ReactDataGrid
                  key={'table1'}
                  style={{padding:'15px'}}
                  columns={meterColumns}
                  rowGetter={i => {
                    return {...this.state.meters[i], _index: i};
                  }}
                  rowsCount={this.state.meters.length}
                  minHeight={500}

                />
              </div>

            </div>
          }
          {/*{
            this.props.editRecord.type === 4 &&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
             工作站
            </span>
              )}>
              {getFieldDecorator('workstation', {
                initialValue: this.props.editRecord ? {
                    key: this.props.editRecord.key,
                    label: this.props.editRecord.name
                  } :
                  {key: '', label: ''},
              })(
                <Select labelInValue={true}>
                  {
                    this.state.all_workstations.map((item, index) => {
                      return <Option key={index} value={item.id.toString()}>{item.name}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
          }*/}
          {
            this.props.editRecord.type === 4 &&
            <div >
              <div style={{padding:'5px 15px 0'}}>{this.renderSimpleFormWorkStation()}</div>
              <div style={{margin:'0 15px'}}>
                <ReactDataGrid
                  key={'table1'}
                  style={{padding:'15px'}}
                  columns={workstationColumns}
                  rowGetter={i => {
                    return {...this.state.all_workstations[i], _index: i};
                  }}
                  rowsCount={this.state.all_workstations.length}
                  minHeight={500}

                />
              </div>

            </div>
          }
          {
            this.props.editRecord.type === 5 &&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
             下级DMA
            </span>
              )}>
              {getFieldDecorator('dma', {
                initialValue: this.props.editRecord ? {
                    value: this.props.editRecord.key,
                    label: this.props.editRecord.name
                  } :
                  {value: '', label: ''},
              })(
                <TreeSelect
                  labelInValue={true}
                  dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                >
                  {this.renderTreeNodes(this.state.villages)}
                </TreeSelect>
              )}
            </FormItem>
          }
          <FormItem
            {...formItemLayoutWithLabel}
            help={'数字越小排在越前'}
            label={(
              <span>
              排序号
            </span>
            )}>
            {getFieldDecorator('sort', {
              initialValue: this.props.editRecord.sort ? this.props.editRecord.sort : 999,
              rules: [{required: true, message: ''}],
            })(
              <InputNumber style={{width: '100%'}}/>
            )}
          </FormItem>
        </Form>
        {
          (this.props.editRecord.type === 6) &&
          <div style={{display: 'flex'}}>

            <div className={'table-data-content-left-table'} style={{flex: 1,background:'#d9c90e'}}>
              <div style={{padding:'5px 15px 0'}}>{this.renderSimpleForm()}</div>
              <div style={{margin:'0 15px'}}>
              <ReactDataGrid
                key={'table1'}
                style={{padding:'15px'}}
                columns={columns}
                rowGetter={i => {
                  return {...data[i], _index: i};
                }}
                rowsCount={data.length}
                minHeight={500}
                rowSelection={{
                  showCheckbox: true,
                  enableShiftSelect: true,
                  onRowsSelected: this.onRowsSelected,
                  onRowsDeselected: this.onRowsDeselected,
                  selectBy: {
                    indexes: selectedRowKeys,
                  },
                }}
                onRowClick={
                  (index, row) => {
                    if (!row) {
                      return;
                    }
                    this.setState({
                      selectedRowKeys: [index]
                    })
                  }
                }

              />
              </div>
              <div className="custom-card" style={{height: 'auto',padding:'0 15px 15px',background:'#d9c90e',}}>
                <div className="table-pagination">
                  <MyPagination searchCondition={{...searchParams}}
                                resetScrollY={() => {
                                }}
                                meta={meta} handleSearch={this.handleSearch}/>
                </div>
              </div>

            </div>
            <div className={'table-data-content'} style={{background:'#49935c',padding:'10px',width:'100px'}}>
              <div style={{display:'flex',height:'100%',alignItems:'center'}}>
                <Button block={true} onClick={this.toRight} icon={'arrow-right'}></Button>
              </div>
              <div>

              </div>

            </div>
            <div className={'table-data-content-right-table'} style={{flex: 1,background:'#0a79c5'}}>
              <div style={{margin:'15px',color:'#fff'}}>
                共{selected_data.length}个水表,已选{filter(selectedSelectedRowKeys,o=>o>=0).length}个水表
                <Button  onClick={this.toLeft} type={'danger'}  icon={'delete'} style={{marginBottom:'5px',marginLeft:'5px'}}>删除所选</Button>
              <ReactDataGrid
                key={'table2'}
                columns={columns2}
                rowGetter={i => {
                  return {...selected_data[i], _index2: i};
                }}
                rowsCount={selected_data.length}
                minHeight={600}
                rowSelection={{
                  showCheckbox: true,
                  enableShiftSelect: true,
                  onRowsSelected: this.onSelectedRowsSelected,
                  onRowsDeselected: this.onSelectedRowsDeselected,
                  selectBy: {
                    indexes: selectedSelectedRowKeys,
                  },
                }}
                onRowClick={
                  (index, row) => {
                    if (!row) {
                      return;
                    }
                    this.setState({
                      selectedSelectedRowKeys: [index]
                    })
                  }
                }

              />
              </div>
            </div>
          </div>
        }
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
